<?php

namespace App\Http\Controllers\Admin;

use App\Models\Goods;
use App\Repositories\BrandRepositories;
use App\Repositories\CategoryRepositories;
use App\Repositories\GoodsParamsRepositories;
use App\Repositories\GoodsRepositories;
use App\Repositories\GoodsTypeRepositories;
use Illuminate\Http\Request;

class GoodsController extends BaseController
{
    private $spec = [];//规格数组
    static $sku_item;//规格
    static $deep_key;//规格深度
    static $total_item;//总规格

    public function __construct(
        GoodsParamsRepositories $goodsParamsRepositories,
        BrandRepositories $brandRepositories,
        CategoryRepositories $categoryRepositories,
        GoodsTypeRepositories $goodsTypeRepositories,
        GoodsRepositories $goodsRepositories
    )
    {
        $this->goodsParamsRepositories = $goodsParamsRepositories;
        $this->brandRepositories =$brandRepositories;
        $this->categoryRepositories =$categoryRepositories;
        $this->goodsTypeRepositories=$goodsTypeRepositories;
        $this->goodsRepositories =$goodsRepositories;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.goods.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $init = $this->initData();
        $f=$this->goodsTypeRepositories->find(1);
        //dump($f->toArray());
        return view('admin.goods.create',compact('init'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       // dd($request->all());
        $ret = $this->goodsRepositories->save($request->all());

        if($ret)
        {
            return redirect()->route('admin.goods')->with(['success'=>'添加完成']);
        }
        return redirect()->back()->with(['success'=>'系统错误']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $init = $this->initData();
        $info =$this->goodsRepositories->find($id);
        //dump($info->toArray());
        $checkArr = [];
        foreach ($info->manyCategory as $key =>$val)
        {
            $checkArr[] = $val->id;
        }

        return view('admin.goods.edit',compact('info','init','checkArr'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request->all());
        $ret = $this->goodsRepositories->update($id,$request->all());

        if($ret)
        {
            return redirect()->route('admin.goods')->with(['success'=>'修改成功']);
        }
        return redirect()->back()->with(['success'=>'系统错误']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy()
    {
       $ids=\request()->input('ids');
       $ret =$this->goodsParamsRepositories->delete($ids);
       if($ret)
       {
           return response()->json([
               'code' => 0,
               'msg'   => '删除成功！',
           ]);
       }
        return response()->json(['ok'=>222]);
    }

    public function data(Request $request)
    {
        $data = $request->all();
        $res = $this->goodsRepositories->search($data);
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    public function category()
    {
        $type = 'goods';
        return view('admin.category.index',compact('type'));
    }

    public function initData()
    {
        return [
            'brand'=>$this->brandRepositories->allBrand(),
            'category'=> $this->categoryRepositories->allCategory('goods'),
            'goods_type'=>$this->goodsTypeRepositories->allGoodsType()
        ];
    }
    public function goodsType($id)
    {
        return $this->goodsTypeRepositories->find($id);
    }

    public function splice (Request $request)
    {
       // dd($request->all());
        $goodsId=$request->input('goods_id',0);

        $spec=$request->input('attributes');
        foreach ($spec as $key => $val) {
            $this->spec[] = $key;
        }
        $items = $this->getSkuItem($request->input('attributes'),-1);

        //此处是需要修改的产品
        if($goodsId > 0) $itemData=$this->getGoodsItemData($goodsId);

        $goodsDefault=[
            'price'=>0,
            'costprice'=>0,
            'market_price'=>0,
            'sn'=>"",
            'stock'=>0,
            'is_defalut'=>0,
            'image_id'=>0
        ];

        foreach ((array)$items as $key => $val)
        {
            if(!empty($itemData))
            {
                if(isset($itemData[$val['spec_name']]))
                {
                    $goodsDefault = $itemData[$val['spec_name']];
                }
                else
                {
                    $goodsDefault=[
                        'price'=>0,
                        'costprice'=>0,
                        'market_price'=>0,
                        'sn'=>"",
                        'stock'=>0,
                        'is_defalut'=>0,
                        'image_id'=>0
                    ];
                }

            }

            $items[$key]['price']     = $goodsDefault['price'];
            $items[$key]['costprice'] = $goodsDefault['costprice'];
            $items[$key]['market_price']  = $goodsDefault['market_price'];
            if (isset($goodsDefault['sn']) && $goodsDefault['sn']) {
                $items[$key]['sn'] = $goodsDefault['sn'] . '-' . ($key + 1);
            }
            else
            {
                $items[$key]['sn']  = $goodsDefault['sn'];
            }
            $items[$key]['stock'] = $goodsDefault['stock'];
            $items[$key]['is_defalut'] = $goodsDefault['is_defalut'];
        }
        return [
            'code' => 0,
            'msg'   => '正在请求中...',
            'data' =>$items,
            'request'  => $request->all()
        ];
    }

    /**
     * @param $data
     * @param int $index
     * @param array $sku_item
     * @return array
     * 此处递归 拼接出 所有规格
     */
    private function getSkuItem($data, $index = -1, $sku_item = [])
    {

        self::$total_item = array();
        if ($index < 0) {
            self::$deep_key = count($data) - 1;

            $this->getSkuItem($data, '0', $sku_item);
        } else {

            if ($index == 0) {

                $first = $data[$this->spec[$index]];

                foreach ($first as $key => $value) {
                    self::$total_item[$key] = array(
                        'spec_name' => $this->spec[$index] . ':' . $value,
                        'spec_key'  => $this->spec[$index],
                    );
                }
            } else {
                $first = $data[$this->spec[$index]];

                if (count($sku_item) >= count($first)) {
                    foreach ($first as $key => $value) {
                        foreach ($sku_item as $s => $v) {

                            self::$total_item[] = array(
                                'spec_name' => $v['spec_name'] . ',' . $this->spec[$index] . ':' . $value,
                                'spec_key'  => $v['spec_key'] . '_' . $this->spec[$index],
                            );
                        }
                    }
                } else {
                    if ($sku_item) {
                        foreach ($sku_item as $key => $value) {
                            foreach ($first as $fkey => $fvalue) {
                                self::$total_item[] = array(
                                    'spec_name' => $value['spec_name'] . ',' . $this->spec[$index] . ':' . $fvalue,
                                    'spec_key'  => $value['spec_key'] . '_' . $this->spec[$index],
                                );
                            }
                        }
                    }
                }
            }
            if ($index < self::$deep_key) {
                $this->getSkuItem($data, $index + 1, self::$total_item);
            }
        }
        return self::$total_item;

    }
    private function getGoodsItemData($goodsId)
    {
        $data=[];
        $res=$this->goodsRepositories->getItemsByGoodsId($goodsId);
        if($res)
        {
            foreach ($res->toArray() as $key=>$val)
            {
                $data[$val['spes_desc']]=$val;
            }

        }
        return $data;


    }
}
